//var QRCode = require('../libs/qrcode.js').QRCode;

String.prototype.toCN = function () {
  var asciicode = this.split("\\u");
  var nativeValue = asciicode[0];
  for (var i = 1; i < asciicode.length; i++) {
    var code = asciicode[i];
    nativeValue += String.fromCharCode(parseInt("0x" + code.substring(0, 4)));
    if (code.length > 4) {
      nativeValue += code.substring(4, code.length);
    }
  }
  return nativeValue.replace(/\\/gim, "");
}

String.prototype.toLocalTime = function (a) {
  var b = new Date;
  return b.setTime(1e3 * parseInt(this)), b.format(a)
};
Date.prototype.format = function (a) {
  var b = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    S: this.getMilliseconds()
  };
  /(y+)/.test(a) && (a = a.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)));
  for (var c in b)
    new RegExp("(" + c + ")").test(a) && (a = a.replace(RegExp.$1, 1 == RegExp.$1.length ? b[c] : ("00" + b[c]).substr(("" + b[c]).length)));
  return a
};
String.prototype.tmpl = function (data) {
  var then = this;
  for (var i in data) {
    var reg = new RegExp("{{" + i + "}}", "gim");
    then = then.replace(reg, data[i]);
  }
  return then;
}
String.prototype.toLocalPic = function () {
  var pic = this;
  ////minimg.hexun.com/i9.hexun.com/2014-09-04/168191562_c162x117.jpg
  var picReg = /\.png|\.jpg|\.gif|\.jpeg/gim,
    isMinImg = /minimg\.hexun\.com/gim,
    d = picReg.exec(pic),
    a = isMinImg.exec(pic);
  pic = !a ? pic != "" ? "https://minimg.hexun.com/" + pic.replace(/http[s]*\:\/\//gim, "").replace(picReg, "") + "_c162x117" + (d && d[0] || ".jpg") : "https://i1.hexun.com/2016/pc/load.png" : pic;

  return pic;
}

var extend = function (a, b) {
  a = a || {};
  for (var i in b) a[i] = b[i];
  return a;
}

module.exports = {
  extend: extend,
  api: {
    list: 'https://bdmw.hexun.com/api/getMoreRecommend?start={{num}}&cnt=20&cateid={{cateid}}&cid={{cid}}',
    newsList: 'https://m.hexun.com/api/getMoreNews?catId={{id}}&count={{count}}',
    asideNews: 'https://opentool.hexun.com/MongodbNewsService/forapp/getrelativenewsJson.jsp?count=6&id={{id}}',
    asideNews_bigData: "https://m.hexun.com/api/getHotNews?id={{id}}&size=6",
    newsView: 'https://opentool.hexun.com/MongodbNewsService/forapp/gethtml.jsp?id={{id}}'
  },
  getChannel: function (cid) {
    return [{
      title: "推荐",
      type: "index",
      path: "index?type=index",
      apiArgs: {
        num: 0,
        cateid: "",
        cid: cid
      }
    }, {
      title: "宏观",
      type: "news",
      path: "index?type=news",
      apiArgs: {
        id: 1,
        count: 0
      }
    }, {
      title: "A股",
      type: "stock",
      path: "index?type=stock",
      apiArgs: {
        id: 2,
        count: 0
      }
    }, {
      title: "科技",
      type: "tech",
      path: "index?type=tech",
      apiArgs: {
        id: 19,
        count: 0
      }
    }, {
      title: "银行",
      type: "bank",
      path: "index?type=bank",
      apiArgs: {
        id: 10,
        count: 0
      }
    }, {
      title: "理财",
      type: "money",
      path: "index?type=money",
      apiArgs: {
        id: 13,
        count: 0
      }
    }, {
      title: "房产",
      type: "house",
      path: "index?type=house",
      apiArgs: {
        id: 17,
        count: 0
      }
    }, {
      title: "汽车",
      type: "auto",
      path: "index?type=auto",
      apiArgs: {
        id: 18,
        count: 0
      }
    }, {
      title: "保险",
      type: "insurance",
      path: "index?type=insurance",
      apiArgs: {
        id: 11,
        count: 0
      }
    }, {
      title: "期货",
      type: "quote_futures",
      path: "index?type=quote_futures",
      apiArgs: {
        id: 6,
        count: 0
      }
    }]
  },
  qrcode: function (selector, options, then) {
    if (!QRCode){
      return ;
    }
    // if options is string, 
    if (typeof options === 'string') {
      options = {
        text: options
      };
    }

    // set default values
    // typeNumber < 1 for automatic calculation
    options = extend({
      render: "canvas",
      width: 256,
      height: 256,
      typeNumber: -1,
      correctLevel: 2,
      background: "#ffffff",
      foreground: "#000000"
    }, options);

    //console.log(options);

    var createCanvas = function (image, callback) {
      // create the qrcode itself
      var qrcode = new QRCode(options.typeNumber, options.correctLevel);
      qrcode.addData(options.text);
      qrcode.make();

      var context = wx.createCanvasContext(image);


      // create canvas element
      //var canvas = document.createElement('canvas');
      //canvas.width = options.width;
      //canvas.height = options.height;
      //var ctx = canvas.getContext('2d');

      // compute tileW/tileH based on options.width/options.height
      var tileW = options.width / qrcode.getModuleCount();
      var tileH = options.height / qrcode.getModuleCount();

      // draw in the canvas
      for (var row = 0; row < qrcode.getModuleCount(); row++) {
        for (var col = 0; col < qrcode.getModuleCount(); col++) {
          context.setFillStyle(qrcode.isDark(row, col) ? options.foreground : options.background);
          var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
          var h = (Math.ceil((row + 1) * tileW) - Math.floor(row * tileW));
          context.fillRect(Math.round(col * tileW), Math.round(row * tileH), w, h);
        }
      }
      context.draw();

      /*wx.drawCanvas({
        //画布标识，传入<canvas/>的cavas-id
        canvasId: image,
        //获取绘制行为， 就相当于你想做到菜context.getActions()就是食材
        actions: context.getActions(),
      })*/
      // return just built canvas
      //image.src = canvas.toDataURL("image/png");
      // return image;
      //context.draw();

      if (callback) {
        return callback(image);
      }
    }

    // from Jon-Carlos Rivera (https://github.com/imbcmdth)
    /*var createTable = function () {
      // create the qrcode itself
      var qrcode = new QRCode(options.typeNumber, options.correctLevel);
      qrcode.addData(options.text);
      qrcode.make();

      // create table element
      var $table = $.createDom("table", {})
        ._css("width", options.width + "px")
        ._css("height", options.height + "px")
        ._css("border", "0px")
        ._css("border-collapse", "collapse")
        ._css('background-color', options.background);

      // compute tileS percentage
      var tileW = options.width / qrcode.getModuleCount();
      var tileH = options.height / qrcode.getModuleCount();

      // draw in the table
      for (var row = 0; row < qrcode.getModuleCount(); row++) {
        var $row = $.createDom('tr', {})._css('height', tileH + "px")._appendTo($table);

        for (var col = 0; col < qrcode.getModuleCount(); col++) {
          $.createDom('td', {})
            ._css('width', tileW + "px")
            ._css('background-color', qrcode.isDark(row, col) ? options.foreground : options.background)
            ._appendTo($row);
        }
      }
      // return just built canvas
      return $table;
    }*/

    createCanvas(selector, function (id) {
      wx.canvasToTempFilePath({
        x: 5,
        y: 5,
        width: 138,
        height: 138,
        destWidth: 128,
        destHeight: 128,
        canvasId: id,
        success: function (res) {
          then && then(res.tempFilePath)
        }
      });
    })
    /*var img = ;

    var element = options.render == "canvas" ? createCanvas(img) : createTable(),
      parent = $.query(selector);
    return parent && parent[0] && $.query(element)[0]._appendTo(parent[0]);*/
  }
}
